package com.example.administrator.kotlin.fragment

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.administrator.kotlin.R
import com.example.administrator.kotlin.adapter.NewsAdapter
import com.example.administrator.kotlin.bean.NewsBean
import com.example.administrator.kotlin.bean.Newslist
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.orhanobut.logger.Logger

/**
 * Created by Administrator on 2018/2/27/027.
 */
class NewsFragment : Fragment() {

    companion object {
        fun newInstance(): NewsFragment {
            return NewsFragment()
        }
    }

    private var datas : List<Newslist>? = null
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: NewsAdapter


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater?.inflate(R.layout.fragment_news, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initData()
        recyclerView = activity.findViewById<RecyclerView>(R.id.recyclerview)
        recyclerView.setHasFixedSize(true)
        recyclerView.layoutManager = LinearLayoutManager(activity)
        adapter = NewsAdapter(activity, R.layout.item_text, datas)
        recyclerView.adapter = adapter
    }

    private fun initData() {
        var url = "http://api.tianapi.com/social/?key=861a794733dd2b057e415d822bef9586&num=3"
        OkGo.get<String>(url)
                .tag("news")
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        var gson: Gson = Gson()
                        val newsBean = gson.fromJson(response?.body().toString(), NewsBean::class.java)
                        val newslist = newsBean.newslist
                        adapter.setNewData(newslist)
                        Logger.i(adapter.itemCount.toString())
                    }

                    override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                        super.onStart(request)
                    }

                    override fun onFinish() {
                        super.onFinish()
                    }

                })

    }
}